from django.db import models
import django.utils.timezone as timezone
from django.contrib.auth.models import (AbstractBaseUser, PermissionsMixin)
from utils.BaseModels import BaseModel
from .manager import UserManager
from django.utils.datetime_safe import date
from records.models import Record


# 会员资料
class UserProfile(BaseModel.FullAtBaseModel, AbstractBaseUser, PermissionsMixin):
    username = models.CharField('登录名', max_length=32, db_index=True, unique=True, default='')
    email = models.EmailField('邮箱', default="", null=True, blank=True, unique=True,)
    name = models.CharField('姓名', max_length=32, db_index=True)
    sex = models.IntegerField('性别', default=1, choices=((1, '女'), (2, '男'),))
    dateOfBirth = models.DateField('出生日期', default=timezone.now,  null=True, blank=True)
    occupation = models.CharField('职业', null=True, max_length=255, blank=True)
    phoneNumber = models.CharField('联系电话', null=True, max_length=12, db_index=True, unique=True)
    address = models.TextField('地址', null=True, blank=True)
    preDeposit = models.DecimalField('预存款', default=0.00, max_digits=12, decimal_places=2)
    totalConsumption = models.DecimalField('总消费额', default=0.00, max_digits=12, decimal_places=2)
    discount = models.DecimalField('折扣', default=1.00, max_digits=3, decimal_places=2)
    openId = models.CharField('微信OpenId', max_length=128, null=True, blank=True, unique=True)
    unionId = models.CharField('微信UnionId', max_length=128, null=True, blank=True, unique=True)
    is_staff = models.BooleanField('是否允许登录后台', default=False)
    is_active = models.BooleanField('是否激活', default=True)
    is_admin = models.BooleanField(verbose_name='是管理员', default=False)
    records = models.ManyToManyField(Record, verbose_name='病史', default=None, null=True, blank=True)
    integral = models.IntegerField('积分', default=0)
    avatar = models.ImageField(upload_to="user/avatar/images/", null=True, blank=True, verbose_name="头像",
                               default='http://up.qqjia.com/z/26/tu32790_17.jpg')

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email']
    objects = UserManager()

    def get_full_name(self):
        return self.name

    def get_short_name(self):
        return self.name

    @property
    def is_authenticated(self):
        return True

    def __str__(self):
        return self.name

    @property
    def age(self):
        return self.calculateAge(self.dateOfBirth)

    age.fget.short_description = '年龄'

    def calculateAge(self, born):
        today = date.today()
        try:
            birthday = born.replace(year=today.year)
        except ValueError:  # raised when birth date is February 29 and the current year is not a leap year
            birthday = born.replace(year=today.year, day=born.day - 1)
        if birthday > today:
            return today.year - born.year
        else:
            return today.year - born.year + 1

    class Meta:
        db_table = 'userprofiles'
        verbose_name = '会员资料管理'
        verbose_name_plural = '会员资料管理'
        permissions = (
            ("test", "测试权限"),
        )

